package org.freez4.spring.configuration.metadata;

import org.freez4.spring.ioc.overview.domain.User;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.MapPropertySource;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 外部化配置示例
 *
 * @author 阿坤同学
 * @date 2024/1/15 4:05 PM
 */
@PropertySource("classpath:/META-INF/user-bean-definitions.properties")
public class PropertySourceDemo {

    private static final Logger logger = Logger.getLogger(PropertySourceDemo.class.getName());

    /**
     * user.name 是 Java Properties 默认存在，当前用户而非properties中的配置属性值。
     */
    @Bean
    public User configuredUser(@Value("${user.id}") Integer id, @Value("${user.name}") String name) {
        User user = new User();
        user.setId(id);
        user.setName(name);
        return user;
    }

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();

        // 扩展 Environment 中的 PropertySources
        // 添加 PropertySource 操作必须在 refresh 方法之前完成
        Map<String, Object> propertiesSource = new HashMap<>();
        propertiesSource.put("user.name", "阿坤同学");
        MapPropertySource propertySource = new MapPropertySource("first-property-source", propertiesSource);
        context.getEnvironment().getPropertySources().addFirst(propertySource);

        // 注册当前类作为 Configuration Class
        context.register(PropertySourceDemo.class);
        // 启动 Spring 应用上下文
        context.refresh();
        // beanName 和 bean 映射
        Map<String, User> usersMap = context.getBeansOfType(User.class);
        for (Map.Entry<String, User> entry : usersMap.entrySet()) {
            logger.log(Level.INFO, () -> "User Bean name :" + entry.getKey() + " content :" + entry.getValue());
        }
        logger.log(Level.INFO, () -> "Environment PropertySources:" + context.getEnvironment().getPropertySources());
        // 关闭 Spring 应用上下文
        context.close();
    }
}